﻿using AutoMapper;
using JTTD.Common.Enum;
using JTTD.DataBase;
using JTTD.Domain.Dtos;
using JTTD.Domain.IService;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JTTD.Common.Helper;
using JTTD.Domain.Dtos.Coupon.Response;
using JTTD.Domain.Dtos.Coupon.Request;

namespace JTTD.Domain.Service
{
    /// <summary>
    /// 商城优惠券服务
    /// </summary>
    public class CouponService : ICouponService
    {
        private readonly JTTDContext _dbContext;
        private readonly IMapper _mapper;
        private readonly IIntegralService _integralService;

        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="mapper"></param>
        /// <param name="integralService"></param>
        public CouponService(JTTDContext context, IMapper mapper, IIntegralService integralService)
        {
            _dbContext = context;
            _mapper = mapper;
            _integralService = integralService;
        }

        /// <summary>
        /// 更改商城优惠券状态
        /// </summary>
        /// <param name="couponNumber"></param>
        /// <param name="isUse"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ChangeUseState(string couponNumber,bool isUse,int? userId=null)
        {
            try
            {
                if(!isUse)
                {
                    var user= await _dbContext.CompanyUserInfoModels.FirstOrDefaultAsync(item=>item.Id==userId.Value&&item.UserType==UserTypeEnum.Admin);
                    if(user!=null)
                    {
                        if(user.IsRevokeCoupon!=1)
                        {
                            return new ApiResult<bool>() { IsSuccess=false,Message="抱歉，当前账号暂无权限执行此操作！"};
                          
                        }
                    }
                    else
                    {
                        return new ApiResult<bool>() { IsSuccess = false, Message = "抱歉，当前账号暂无权限执行此操作！" };
                    }
                }
                var coupon = await _dbContext.CouponInfoModels.FirstOrDefaultAsync(item => item.CouponNumber == couponNumber.Trim());
                if (coupon == null)
                {
                    throw new Exception("没有找到指定的商城优惠券");
                }
                coupon.IsUse = isUse;
                _dbContext.CouponInfoModels.Update(coupon);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }

        /// <summary>
        /// 兑换商城优惠券
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ExchangeCoupon(int userId, decimal amount)
        {
            try
            {
                //验证用户是否存在
                var user = await _dbContext.UserInfos.FindAsync(userId);
                if (user == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                var arrys = new[] { ConfigTypeEnum.CouponDayExchangeNum, ConfigTypeEnum.CouponDayExchangeTotalAmount, ConfigTypeEnum.CouponExchangeRatio, ConfigTypeEnum.CouponOutTimeDayNum };
                var configList = await _dbContext.ConfigInfoModels.Where(item => arrys.Contains(item.Key)).ToListAsync();
                if (!configList.Any())
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "系统尚未初始化" };
                }
                //验证积分兑换优惠券金额比例设置是否存在
                var couponExchangeRatio = configList.FirstOrDefault(item => item.Key == ConfigTypeEnum.CouponExchangeRatio);
                if (couponExchangeRatio == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = $"系统尚未初始化{ConfigTypeEnum.CouponExchangeRatio.GetDescription()}设置" };
                }
                //验证用户积分余额是否能够兑换优惠券
                var integral = await _integralService.GetUserIntegral(user.Id);
                if (amount * Convert.ToDecimal(couponExchangeRatio.Value) > integral)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "当前账户积分余额不足以兑换" };
                }
                //验证优惠券有效期天数设置是否存在
                var couponOutTimeDayNum = configList.FirstOrDefault(item => item.Key == ConfigTypeEnum.CouponOutTimeDayNum);
                if (couponOutTimeDayNum == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = $"系统尚未初始化{ConfigTypeEnum.CouponOutTimeDayNum.GetDescription()}设置" };
                }
                DateTime startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                DateTime endTime = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"));
                bool isWeekDay = DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday;
                //验证当前用户当天兑换优惠券次数是否超过上限（不包含管理员赠送优惠券）
                var couponDayExchangeNum = isWeekDay ? configList.FirstOrDefault(item => item.Key == ConfigTypeEnum.CouponWeekendDayExchangeNum) : configList.FirstOrDefault(item => item.Key == ConfigTypeEnum.CouponDayExchangeNum);
                if (couponDayExchangeNum != null)
                {
                    int count = await _dbContext.CouponInfoModels.CountAsync(item => item.Source == CouponSourceEnum.IntegralExChange && item.UserId == userId && startTime <= item.CreateTime && item.CreateTime <= endTime);
                    if (count >= Convert.ToInt32(couponDayExchangeNum.Value))
                    {
                        return new ApiResult<bool> { IsSuccess = false, Message = $"抱歉，每天只能兑换{couponDayExchangeNum.Value}张优惠券" };
                    }
                }
                //验证当前用户当天兑换优惠券总金额是否超过上限（不包含管理员赠送优惠券）
                var couponDayExchangeTotalAmount = isWeekDay ? configList.FirstOrDefault(item => item.Key == ConfigTypeEnum.CouponWeekendDayExchangeTotalAmount) : configList.FirstOrDefault(item => item.Key == ConfigTypeEnum.CouponDayExchangeTotalAmount);
                if (couponDayExchangeTotalAmount != null)
                {
                    decimal totalAmount = await _dbContext.CouponInfoModels.Where(item => item.Source == CouponSourceEnum.IntegralExChange && item.UserId == userId && startTime <= item.CreateTime && item.CreateTime <= endTime).SumAsync(item => item.Amount);
                    if (totalAmount + amount > Convert.ToDecimal(couponDayExchangeTotalAmount.Value))
                    {
                        return new ApiResult<bool> { IsSuccess = false, Message = $"抱歉，每天只能兑换总金额为{couponDayExchangeTotalAmount.Value}的优惠券" };
                    }
                }
                var model = new DataBase.Model.Coupon.CouponInfoModel
                {
                    Amount = amount,
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now.AddDays(Convert.ToInt32(couponOutTimeDayNum.Value)),
                    UserId = userId,
                    IsUse = false,
                    Source = CouponSourceEnum.IntegralExChange
                };
                _dbContext.Database.BeginTransaction();
                //添加优惠券
                _dbContext.CouponInfoModels.Add(model);
                //更新用户积分余额
                //user.Integral = user.Integral - amount * Convert.ToDecimal(couponExchangeRatio.Value);
                _dbContext.UserInfos.Update(user);
                //添加积分收支记录
                var recordModel = new DataBase.Model.Integral.IntrgralRecordModel();

                recordModel.UserId = userId;
                recordModel.Type = RecordTypeEnum.Expenditure;
                recordModel.Integral = amount * Convert.ToDecimal(couponExchangeRatio.Value);
                recordModel.OperatingTime = DateTime.Now;
                recordModel.Before =await  _integralService.GetUserIntegral(userId);
                recordModel.After = recordModel.Before - recordModel.Integral;

                _dbContext.IntrgralRecords.Add(recordModel);
                await _dbContext.SaveChangesAsync();
                _dbContext.Database.CommitTransaction();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败," + ex.Message };
            }
        }

        /// <summary>
        /// 分页获取指定用户能使用的商城优惠券
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<CouponInfoResponseDto>>> GetCouponPageList(int userId, BaseSearch dto)
        {
            try
            {
                var query = _dbContext.CouponInfoModels.Where(item => item.UserId == userId && !item.IsUse && item.EndTime > DateTime.Now).OrderBy(item => item.EndTime).ThenByDescending(item => item.Amount);
                int count = await query.CountAsync();
                if (count > 0)
                {
                    var list = await query.OrderBy(item => item.EndTime).ThenByDescending(item => item.Amount).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
                    return new ApiResult<PageResult<CouponInfoResponseDto>>()
                    {
                        IsSuccess = true,
                        Data = new PageResult<CouponInfoResponseDto>
                        {
                            Data = _mapper.Map<List<CouponInfoResponseDto>>(list),
                            PageIndex = dto.PageIndex,
                            PageSize = dto.PageSize,
                            TotalNum = count,
                            TotalPageNum = (count % dto.PageSize) == 0 ? count / dto.PageSize : count / dto.PageSize + 1
                        }
                    };
                }
                else
                {
                    return new ApiResult<PageResult<CouponInfoResponseDto>>()
                    {
                        Data = new PageResult<CouponInfoResponseDto>()
                        {
                            PageIndex = dto.PageIndex,
                            PageSize = dto.PageSize,
                            Data = new List<CouponInfoResponseDto>()
                        },
                        IsSuccess = true,
                        Message = "暂无可使用的商城优惠券"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<PageResult<CouponInfoResponseDto>>()
                {
                    IsSuccess = false,
                    Message = "查询失败，" + ex.Message
                };
            }
        }


        /// <summary>
        /// 赠送商城优惠券
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> SendCoupon(int userId, decimal amount)
        {
            try
            {
                //验证用户是否存在
                var user = await _dbContext.UserInfos.FindAsync(userId);
                if (user == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                var timeDayNumConfig = await _dbContext.ConfigInfoModels.FirstOrDefaultAsync(item => item.Key == ConfigTypeEnum.CouponOutTimeDayNum);
                if (timeDayNumConfig == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = $"系统尚未初始化{ConfigTypeEnum.CouponOutTimeDayNum.GetDescription()}设置" };
                }

                var model = new DataBase.Model.Coupon.CouponInfoModel
                {
                    Amount = amount,
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now.AddDays(Convert.ToInt32(timeDayNumConfig.Value)),
                    UserId = userId,
                    IsUse = false,
                    Source = CouponSourceEnum.AdminGive
                };
                _dbContext.CouponInfoModels.Add(model);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }

        /// <summary>
        /// 分页获取所有停车优惠券
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<CouponInfoResponseDto>>> GetAllCouponPageList(CouponSearchRequestDto dto)
        {
            var query = _dbContext.CouponInfoModels.Where(item => true);
            if (dto.IsUse.HasValue)
            {
                query = query.Where(item => item.IsUse == dto.IsUse.Value);
            }
            if (!string.IsNullOrWhiteSpace(dto.CouponNumber))
            {
                query = query.Where(item => item.CouponNumber == dto.CouponNumber.Trim());
            }
            if (!string.IsNullOrWhiteSpace(dto.Phone))
            {
                var user = await _dbContext.UserInfos.FirstOrDefaultAsync(item => item.Phone == dto.Phone.Trim());
                if (user == null)
                {
                    return new ApiResult<PageResult<CouponInfoResponseDto>>
                    {
                        IsSuccess = true,
                        Message = "暂无可使用的商城优惠券",
                        Data = new PageResult<CouponInfoResponseDto>()
                    };
                }
                else
                {
                    query = query.Where(item => item.UserId == user.Id);
                }
            }
            int count = await query.CountAsync();
            if (count > 0)
            {
                var list = await query.OrderBy(item => item.EndTime).ThenByDescending(item => item.Amount).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
                var userIds = list.Select(item => item.UserId).ToArray();
                var userList = await _dbContext.UserInfos.Where(item => userIds.Contains(item.Id)).ToListAsync();
                var tempList = _mapper.Map<List<CouponInfoResponseDto>>(list);
                foreach (var item in tempList)
                {
                    item.UserNumber = userList.FirstOrDefault(args => args.Id == item.UserId)?.UserNumber;
                }
                return new ApiResult<PageResult<CouponInfoResponseDto>>()
                {
                    IsSuccess = true,
                    Data = new PageResult<CouponInfoResponseDto>
                    {
                        Data = tempList,
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize,
                        TotalNum = count,
                        TotalPageNum = (count % dto.PageSize) == 0 ? count / dto.PageSize : count / dto.PageSize + 1
                    }
                };
            }
            else
            {
                return new ApiResult<PageResult<CouponInfoResponseDto>>()
                {
                    Data = new PageResult<CouponInfoResponseDto>()
                    {
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize,
                        Data = new List<CouponInfoResponseDto>()
                    },
                    IsSuccess = true,
                    Message = "暂无可使用的商城优惠券"
                };
            }
        }

        /// <summary>
        /// 删除商城优惠券
        /// </summary>
        /// <param name="couponNumber"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async  Task<ApiResult<bool>> DeleteCoupon(string couponNumber,int userId)
        {
            var user = await _dbContext.CompanyUserInfoModels.FirstOrDefaultAsync(item => item.Id == userId && item.UserType == UserTypeEnum.Admin);
            if (user != null)
            {
                if (user.IsRevokeCoupon != 1)
                {
                    return new ApiResult<bool>() { IsSuccess = false, Message = "抱歉，当前账号暂无权限执行此操作！" };

                }
            }
            else
            {
                return new ApiResult<bool>() { IsSuccess = false, Message = "抱歉，当前账号暂无权限执行此操作！" };
            }
            var coupon=await   _dbContext.CouponInfoModels.Where(item => item.CouponNumber == couponNumber).FirstOrDefaultAsync();
            if(coupon==null)
            {
                return new ApiResult<bool>() { IsSuccess=false,Message="操作失败，没有找到对应优惠券！"};
            }
            if(coupon.IsUse)
            {
                return new ApiResult<bool>() { IsSuccess=false,Message="已核销优惠券不能进行此操作"};
            }
            _dbContext.CouponInfoModels.Remove(coupon);
            await _dbContext.SaveChangesAsync();
            return new ApiResult<bool>() { IsSuccess = true, Message="操作成功！" };
        }



    }
}